package cn.zstu.seckill.mq;

import cn.zstu.seckill.bo.GoodsBo;
import cn.zstu.seckill.entity.SeckillOrder;
import cn.zstu.seckill.entity.User;
import cn.zstu.seckill.mail.MailDto;
//import cn.zstu.seckill.mail.MailService;
import cn.zstu.seckill.mail.MailService;
import cn.zstu.seckill.redis.RedisService;
import cn.zstu.seckill.service.OrderService;
import cn.zstu.seckill.service.SeckillGoodsService;
import cn.zstu.seckill.service.SeckillOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

@Service
public class MQReceiver {

		private static Logger log = LoggerFactory.getLogger(MQReceiver.class);
		
		@Autowired
		RedisService redisService;
		
		@Autowired
		SeckillGoodsService goodsService;
		
		@Autowired
		OrderService orderService;
		
		@Autowired
		SeckillOrderService seckillOrderService;

		@Autowired
		private MailService mailService;

		@Autowired
		private Environment env;

		@Autowired
		MQSender mqSender;
		
		@RabbitListener(queues=MQConfig.MIAOSHA_QUEUE)
		public void receive(String message) {
			log.info("receive message:"+message);
			SeckillMessage mm  = RedisService.stringToBean(message, SeckillMessage.class);
			User user = mm.getUser();
			long goodsId = mm.getGoodsId();
			
			GoodsBo goods = goodsService.getseckillGoodsBoByGoodsId(goodsId);
	    	int stock = goods.getStockCount();
	    	if(stock <= 0) {
	    		return;
	    	}
	    	//判断是否已经秒杀到了
	    	SeckillOrder order = seckillOrderService.getSeckillOrderByUserIdGoodsId(user.getId(), goodsId);
	    	if(order != null) {
	    		return;
	    	}
	    	//减库存 下订单 写入秒杀订单
			seckillOrderService.insert(user, goods);

	    	//订单成功后mail入队，准备发送邮件服务
			MailMessage mailMessage = new MailMessage();
			mailMessage.setUser(user);
			//获取订单
			order = seckillOrderService.getSeckillOrderByUserIdGoodsId(user.getId(), goodsId);
			mailMessage.setOrder(order);
			mailMessage.setGoodsBo(goods);
			mqSender.sendMailMessage(mailMessage);
		}

		/**
		 * 秒杀异步邮件通知-接收消息
		 * ,containerFactory = "singleListenerContainer"
		 */
		@RabbitListener(queues = MQConfig.MAIL_QUEUE)
		public void consumeEmailMsg(MailMessage info){
			try {
				log.info("秒杀异步邮件通知-接收消息:{}",info);

				//TODO:真正的发送邮件....
				//简单文本
				//MailDto dto=new MailDto(env.getProperty("mail.kill.item.success.subject"),"这是测试内容",new String[]{info.getEmail()});
				//mailService.sendSimpleEmail(dto);

				//花哨文本
				final String content=String.format("%s：您好，您已成功抢购到商品: <strong style=\"color: red\">%s</strong> ，复制该链接并在浏览器采用新的页面打开，即可查看抢购详情：http://localhost:8888/order_detail.htm?orderId=%s，并请您在1个小时内完成订单的支付，超时将失效该订单哦！祝你生活愉快！",info.getUser().getUserName(),info.getGoodsBo().getGoodsName(),info.getOrder().getId());
				MailDto dto=new MailDto("商品抢购成功",content,new String[]{"304317107@qq.com"});
//				final String content=String.format(env.getProperty("mail.kill.item.success.content"),info.getUser().getUserName(),info.getGoodsBo().getGoodsName(),info.getOrder().getId());
//				MailDto dto=new MailDto(env.getProperty("mail.kill.item.success.subject"),content,new String[]{info.getUser().getMail()});
				mailService.sendHTMLMail(dto);

			}catch (Exception e){
				log.error("秒杀异步邮件通知-接收消息-发生异常：",e.fillInStackTrace());
			}
		}

}
